package command;

import util.ConfigEnum;
import util.ConfigurationManager;
import util.MessageEnum;
import util.MessageManager;

import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AppServlet extends HttpServlet {
    private final String UPLOAD_DIRECTORY = "C:/uploads";
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException   {
        processRequest(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = null;
            System.out.println("starttttt");
     CommandFactory.d();
      Command command =null;
            try {

            System.out.println("____");

            command= CommandFactory.getCommand(request);
            System.out.println("finnnish");
           page = command.execute(request, response);
        } catch (ServletException e) {

                System.out.print(e);
            e.printStackTrace();
            request.setAttribute("errorMessage",
                    MessageManager.getInstance().getProperty(
                            MessageEnum.SERVLET_EXCEPTION_ERROR_MESSAGE));
            page = ConfigurationManager.getInstance().
                    getProperty(ConfigEnum.ERROR_PAGE_PATH);
        } catch (IOException e) {
                System.out.print(e);
            e.printStackTrace();
            request.setAttribute("errorMessage",
                    MessageManager.getInstance().
                            getProperty(MessageEnum.IO_EXCEPTION_ERROR_MESSAGE));
        } catch (ClassNotFoundException e) {

                System.out.print(e);
            e.printStackTrace();
            request.setAttribute("errorMessage",
                    MessageManager.getInstance().
                            getProperty(MessageEnum.IO_EXCEPTION_ERROR_MESSAGE));

        } catch (SQLException e) {

                System.out.print(e);
            e.printStackTrace();
            request.setAttribute("errorMessage",
                    MessageManager.getInstance().
                            getProperty(MessageEnum.IO_EXCEPTION_ERROR_MESSAGE));
        }

        if (page != null) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
            dispatcher.forward(request, response);
        } else {
            return;
        }
    }

}
